<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 110px">
            <el-option label="调整单号" value="adjust_no"></el-option>
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="来源单号" value="source_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" @search="query" class="w-60" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <VBatchInput v-model="form.skuInfo.value" @search="query" class="w-60" />
        </VGroup>
        <VSelect v-model="form.destination_warehouse" placeholder="目的仓库" type="warehouse156" multiple collapse-tags
          filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.adjust_status" placeholder="审核状态" :options="options.adjust_status || []" multiple
          collapse-tags filterable clearable style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="申请时间" value="create_time"></el-option>
            <el-option label="审核时间" value="audit_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VAudit
          :auth="['/purchase/manage/adjust/planAudit', '/purchase/manage/adjust/purchaseAudit', '/purchase/manage/adjust/manageAudit']"
          field="pa_id" url="/v1/purchase/purchase-adjust/batch-audit" :tableRef="tableRef"
          :list="options.batch_audit_status" @success="query" />
        <VButton auth="/purchase/manage/adjust/cancel" @click="handleBatch('cancel')">批量作废</VButton>
        <VExport auth="/purchase/manage/adjust/export" mainKey="pa_id" name="adjust" :tableRef="tableRef" task
          class="ml-auto" />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <VLog ref="logRef" />
    <Confirm ref="confirmRef" @success="query" />
  </VPage>
</template>
  
<script setup lang="jsx">
import api from './api'
import Confirm from './components/Confirm'
import Add from './components/Add'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'

const baseName = 'purchase_adjust'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  getOption({ type: 'payment' }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] }),
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const pa_ids = selection.map(d => d.pa_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    cancel: () => {
      ElMessageBox.confirm('是否确认作废？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.cancel({ pa_ids }).then(res => {
            ElMessage.success('操作成功')
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
  }
  handle[name]()
}

// 单行操作
const confirmRef = ref()
const addRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { pa_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    look: () => {
      addRef?.value.open(pa_id, { look: true })
    },
    edit: () => {
      addRef?.value.open(pa_id)
    },
    submit: () => {
      showLoading()
      api.submit({ pa_id }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    confirm1: () => {
      confirmRef?.value.open(pa_id, { title: '待采购确认', http: api.purchaseConfirm })
    },
    confirm2: () => {
      confirmRef?.value.open(pa_id, { title: '待财务确认', http: api.financeConfirm })
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.cancel({ pa_ids: [pa_id] }).then(res => {
            ElMessage.success('操作成功')
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, pa_id })
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 92 },
  showHeaderOverflow: false,
  formConfig: {
    data: {
      input: { type: 'adjust_no', value: '' },
      skuInfo: { type: 'sku', value: '' },
      dateRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      width: 150, slots: {
        header: () => <div>调整单号</div>,
        default: ({ row }) => <div>
          <el-link type='primary'>{row.adjust_no}</el-link>
        </div>
      }
    },
    {
      width: 150, slots: {
        header: () => <div>来源类型<br />来源单号</div>,
        default: ({ row }) => <div>
          <div>{row.source_type_name}</div>
          <el-link type='primary'>{row.source_no}</el-link>
        </div>
      }
    },
    {
      width: 160, slots: {
        header: () => <div>采购单信息</div>,
        default: ({ row }) => <div>
          <div><el-link type='primary'>{row.purchase_no}</el-link></div>
          <VText title='类型'>{row.purchase_type_name}</VText>
          <VText title='采购状态'>{row.purchase_status_name}</VText>
          <VText title='财务状态'>{row.finance_status_name}</VText>
        </div>
      }
    },
    {
      width: 100, slots: {
        header: () => <div>sku</div>,
        default: ({ row }) => <div>
          <div>{row.sku}</div>
        </div>
      }
    },
    {
      title: '图片', width: 100, slots: {
        default: ({ row }) => <VImage src={row.main_img} size="80px"></VImage>
      }
    },
    {
      width: 240, slots: {
        header: () => <div>供应商信息</div>,
        default: ({ row }) => <div>
          <VText title='供应商'>{row.supplier_name}</VText>
          <VText title='供应商id' value={row.supplier_code} />
          <VText title='供应商类型'>{row.purchase_type_name}</VText>
          <VText title='结算方式' value={row.period_name} line={1}></VText>
        </div>
      }
    },
    {
      width: 170, slots: {
        header: () => <div>调整申请人<br />调整申请时间</div>,
        default: ({ row }) => <div>
          <div>{row.create_user}</div>
          <div>{row.create_time}</div>
        </div>
      }
    },
    {
      width: 240, slots: {
        header: () => <div>调整信息</div>,
        default: ({ row }) => <div>
          <VText title='原主体' value={row.adjust_info.origin_company_name} line={1}></VText>
          <VText title='调整后主体' value={row.adjust_info.adjust_company_name} line={1}></VText>
          <VText title='是否退税'>{row.adjust_info.is_drawback_name}</VText>
          <VText title='调整金额'>{row.adjust_info.adjust_price}</VText>
        </div>
      }
    },
    {
      width: 150, slots: {
        header: () => <div>调整原因</div>,
        default: ({ row }) => <VText value={row.adjust_reason} line={3} />
      }
    },
    {
      width: 150, slots: {
        header: () => <div>审核状态</div>,
        default: ({ row }) => <VText value={row.adjust_status_name} line={3} />
      }
    },
    {
      width: 150, slots: {
        header: () => <div>审核备注</div>,
        default: ({ row }) => <VText value={row.audit_remark} line={3} />
      }
    },
    {
      width: 170, slots: {
        header: () => <div>审核人<br />审核时间</div>,
        default: ({ row }) => <div>
          <div>{row.audit_user}</div>
          <div>{row.audit_time}</div>
        </div>
      }
    },
    {
      title: '操作', width: 120, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { adjust_status } = row
          // adjust_status	审核状态1待提交2待计划经理审核3已审核4已驳回5已作废6待采购确认7待采购经理审核8待财务确认
          return [<div class='nm flex flex-wrap gap-x-2 gap-y-1'>
            <VButton auth="/purchase/manage/adjust/detail" link type="primary" onClick={() => handleRow('look', row)}>查看</VButton>
            {[1, 4].includes(adjust_status) ? <VButton auth="/purchase/manage/adjust/edit" link type="primary" onClick={() => handleRow('edit', row)}>编辑</VButton> : ''}
            {[1, 4].includes(adjust_status) ? <VButton auth="/purchase/manage/adjust/submit" link type="primary" onClick={() => handleRow('submit', row)}>提交</VButton> : ''}
            {[6].includes(adjust_status) ? <VButton auth="/purchase/manage/adjust/purchaseConfirm" link type="primary" onClick={() => handleRow('confirm1', row)}>待采购确认</VButton> : ''}
            {[8].includes(adjust_status) ? <VButton auth="/purchase/manage/adjust/financeConfirm" link type="primary" onClick={() => handleRow('confirm2', row)}>待财务确认</VButton> : ''}
            {[1, 4].includes(adjust_status) ? <VButton auth="/purchase/manage/adjust/cancel" link type="primary" onClick={() => handleRow('cancel', row)}>作废</VButton> : ''}
            <VButton auth="/purchase/manage/adjust/log" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
          </div>]
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  